<template>
  <div class="ProductReviewListTags">
    <van-tag round size="large"
             :color="renderTagColor(0)"
             :text-color="renderTagTextColor(0)"
             @click="handleTagClick(0)" v-if="allCount !== 0">
      全部({{ allCount }})
    </van-tag>
    <van-tag round size="large"
             :color="renderTagColor(1)"
             :text-color="renderTagTextColor(1)"
             @click="handleTagClick(1)" v-if="rating2 !== 0">
      好评({{ rating2 }})
    </van-tag>
    <van-tag round size="large"
             :color="renderTagColor(2)"
             :text-color="renderTagTextColor(2)"
             @click="handleTagClick(2)" v-if="rating1 !== 0">
      中评({{ rating1 }})
    </van-tag>
    <van-tag round size="large"
             :color="renderTagColor(3)"
             :text-color="renderTagTextColor(3)"
             @click="handleTagClick(3)" v-if="rating0 !== 0">
      差评({{ rating0 }})
    </van-tag>
  </div>
</template>

<script>
import { catalog } from "@mall/api-services"
import { Tag } from "vant"

const RATING0 = [0, 1]
const RATING1 = [2, 3]
const RATING2 = [4, 5]

export default {
  name: "ProductReviewListTags",
  components: {
    [Tag.name]: Tag,
  },
  props: {
    productId: String,
  },
  data() {
    return {
      activeTag: 0,
      allCount: 0,
      rating0: 0,
      rating1: 0,
      rating2: 0,
    }
  },
  created() {
    this.fetchRating(RATING0).then(rating => this.rating0 = rating)
    this.fetchRating(RATING1).then(rating => this.rating1 = rating)
    this.fetchRating(RATING2).then(rating => this.rating2 = rating)
    this.fetchAll().then(rating => this.allCount = rating)
  },
  methods: {
    renderTagColor(tag) {
      return this.activeTag === tag ? "rgba(238, 10, 36, 0.1)" : "rgb(247, 248, 250)"
    },
    renderTagTextColor(tag) {
      return this.activeTag === tag ? "rgb(238, 10, 36)" : "#323233"
    },
    fetchAll() {
      const { productId } = this
      return catalog.ReviewServiceV1.createReviewQuery().productId(productId).count()
    },
    fetchRating(ratings) {
      const { productId } = this
      return catalog.ReviewServiceV1
          .createReviewQuery()
          .productId(productId).ratings(ratings)
          .count()
    },
    handleTagClick(tag) {
      this.activeTag = tag
      if (tag === 0) {
        this.$emit("ratings-change", [])
      } else if (tag === 1) {
        this.$emit("ratings-change", RATING2)
      } else if (tag === 2) {
        this.$emit("ratings-change", RATING1)
      } else if (tag === 3) {
        this.$emit("ratings-change", RATING0)
      }
    },
  },
}
</script>

<style lang="scss" scoped>

.ProductReviewListTags {
  .van-tag {
    padding: 4px 10px;
    margin-right: 12px;

    &:last-child {
      margin-right: 0;
    }
  }
}
</style>
